package com.system.employee.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.system.employee.dao.EmployeeRepository;
import com.system.employee.entity.Employee;
import com.system.transfer.dao.TransferRepository;
import com.system.transfer.entity.Transfer;
import com.system.user.dao.UserRepository;
import com.system.user.entity.User;



@Service
@Transactional
public  class EmployeeService implements IEmployeeService {
	@Autowired	
	EmployeeRepository employeeRepository;
	@Autowired
	UserRepository userRepository;
	@Autowired
	private TransferRepository transferRepository;
	
	public void saveOrUpdate(Employee employee) {
		if(employee.getEmpId()!=null) {
		Employee temp=employeeRepository.findOne(employee.getEmpId());
		if(temp!=null) {
		
			if(temp.getUser()!=null) {
				employee.setUser(temp.getUser());
			}
			if(temp.getPost()!=null) {
				employee.setPost(temp.getPost());
			}
				
			
		}
		}
		        userRepository.save(employee.getUser());
				employeeRepository.save(employee);
			
		
	}
	public void delete(Employee employee) {
		List<Transfer> t=(List<Transfer>) transferRepository.findTransferByEmployee(employee.getEmpId());
		if(t!=null)
		transferRepository.delete(t);//先删除调动记录
		employeeRepository.delete(employee);
	}
	public void delete(List<Long> ids) {
		List<Employee> employees =  (List<Employee>) employeeRepository.findAll(ids);
		for(Employee e:employees) {
			List<Transfer> t=(List<Transfer>)transferRepository.findTransferByEmployee(e.getEmpId());
			if(t!=null)
			transferRepository.delete(t);//先删除调动记录
		}
		
		if(employees!=null) {
			employeeRepository.delete(employees);
		}
	}
	@Transactional(readOnly = true)
	public Employee findOne(Long id) {
		return employeeRepository.findOne(id);
	}
	@Transactional(readOnly = true)
	public List<Employee> findAll(){
		return (List<Employee>) employeeRepository.findAll();
	}

	//动态条件查询
	@Transactional(readOnly = true)
	public Page<Employee> findAll(Specification<Employee> spec, Pageable pageable){
		return employeeRepository.findAll(spec, pageable);
	}
	@Override
	public Employee findUser(User user) {
		Employee e = employeeRepository.findEmployeeByUser(user);
		return e;
	}

	public Employee findEmployeeByEmpName(String empName) {
		return employeeRepository.findEmployeeByEmpName(empName);
	}
	public List<Employee> findByEmpNameLike(String empName){
		return (List<Employee>)employeeRepository.findEmployeeByEmpNameLike(empName);
	}
}
